const fs = require('fs');
module.exports = class
{

    /**
     *
     * @param upFile thinkjs的文件对象
     * @param savePath 文件保存路径(绝对 ) think.ROOT_PATH+'/www/uploads/imgs/';
     */
    constructor(upFile, savePath)
    {
        this.relativePath = '/uploads/imgs/';
        this.fileSavePath = savePath;//文件保存路径
        this.tempPath = upFile.path;//上传文件临时路径
        this.fileSize = upFile.size;//文件大小
        this.fileType = upFile.type;//文件类型
        this.fileName = upFile.name;//文件原始名称
        this.fileExt = this.fileName.split('.').slice(-1)[0];//文件扩展名
        let timeStamp = Date.parse(new Date());//时间戳
        this.fileNewName = think.md5(this.fileName + timeStamp) + "." + this.fileExt;//文件新名称
        this.upImgSaveFileName = this.fileSavePath + this.fileNewName;  //文件保存全路径
    }

    /**
     * 保存上传文件
     * 同步的
     * @returns {Promise.<void>}
     */
    save(allowExt = [])
    {
        fs.renameSync(this.tempPath, this.upImgSaveFileName);
        if (fs.existsSync(this.upImgSaveFileName) === true)
        {
            //文件上传成功

            return {
                'filename': this.fileName,
                'fileNewName': this.fileNewName,
                'fileExt': this.fileExt,
                'saveFile': this.relativePath + this.fileNewName,
                'fileSize': this.fileSize,
                'fileType': this.fileType,
                'status': '文件上传成功',

            }
        }
        //文件上传失败
        return {
            'status': '文件上传失败'
        }

    }
};